// pages/exercise/random.js
const db = wx.cloud.database()
var app = getApp();
Page({
  data: {
    index: 0,
    openid:'',
    questionList: [],
    showModal: false,
    beginTime: 0
  },
  swiper: function(e){
    var current = e.detail.current
    if(current == this.data.questionList.length){
      current = 0
    }
    this.setData({
      index: current
    })
  },
  //单选题
  choose: function(e){
    var that = this
    var option = e.currentTarget.dataset.option
    var type = e.currentTarget.dataset.type
    var idx = e.currentTarget.dataset.idx //题目下标
    var questionList = that.data.questionList
    if(type == '1'){
      if(!questionList[idx].choosed){
        questionList[idx].choosed = option
        that.setData({
          index: that.data.index + 1,
          questionList
        })

        //选择错误 => 记录错题本
        if(option != questionList[idx].answer){
          console.log('正确答案',questionList[idx].answer)
          var question = questionList[idx]
          //检查是否已经插入过
          db.collection('userWrong').where({
            _openid: that.data.openid,
            'question._id':question._id
          }).get({
            success: res => {
              console.log(res.data)
              if(!res.data.length){
                db.collection('userWrong').add({
                  data:{
                    question
                  },
                  success: res => {
                    console.log(res._id)
                  },
                  fail: err => {
                    console.error('新增失败：', err)
                  }
                })
              }else{
                //修改答案
                db.collection('userWrong').doc(res.data[0]._id).update({
                  data:{
                    'question.choosed': option
                  }
                })
              }
            },
            fail: err => {
              console.error('查询失败：', err)
            }
          })
          
        }else{
          //选择正确 => 删除错题本的题目
          console.log(that.data.openid,questionList[idx]._id)
          db.collection('userWrong').where({
            _openid: that.data.openid,
            'question._id': questionList[idx]._id
          }).remove()
        }
      }
      if(that.data.index == questionList.length){
        that.setData({
          showModal: true
        })
      }
      
    }else{
      if(!questionList[idx].answered){
        var choosed =  questionList[idx].choosed || []
        var index = choosed.indexOf(option)
        if(index == -1){
          choosed.push(option) 
        }else{
          choosed.splice(index,1)
        }
        questionList[idx].choosed = choosed.sort()
        that.setData({
          questionList: questionList
        })
      }
      
    }
    
  },
  chooseMulti: function(e){
    var that = this
    var idx = e.currentTarget.dataset.idx //题目下标
    var questionList = that.data.questionList 
    if(questionList[idx].choosed){
      questionList[idx].answered = true
      that.setData({
        questionList: questionList
      })
      //记录错题本
      if(JSON.stringify(questionList[idx].choosed) != JSON.stringify(questionList[idx].answer)){
        console.log('正确答案',questionList[idx].answer)
        var question = questionList[idx]
        //检查是否已经插入过
        db.collection('userWrong').where({
          _openid: that.data.openid,
          'question._id':question._id
        }).get({
          success: res => {
            if(!res.data.length){
              db.collection('userWrong').add({
                data:{
                  question
                },
                success: res => {
                  console.log(res._id)
                },
                fail: err => {
                  console.error('失败：', err)
                }
              })
            }else{
              //修改答案
              // console.log('更新_id:',res.data[0]._id)
              // console.log('待更新的答案:',questionList[idx].choosed)
              db.collection('userWrong').doc(res.data[0]._id).update({
                data:{
                  'question.choosed': questionList[idx].choosed
                }
              })
            }
          },
          fail: err => {
            console.error('查询失败：', err)
          }
        })
        
      }else{
        //选择正确 => 删除错题本的题目
        console.log(that.data.openid,questionList[idx]._id)
        db.collection('userWrong').where({
          _openid: that.data.openid,
          'question._id': questionList[idx]._id
        }).remove()
      }
      if(that.data.index == questionList.length-1){
        that.setData({
          showModal: true
        })
      }else{
        that.setData({
          index: that.data.index + 1,
        })
        
      }
    }
    
  },
  jump: function(e){
    var current = e.currentTarget.dataset.current
    this.setData({
      index: current,
      showModal: false
    })
  },
  //交卷
  submitTest: function(){

    var that = this
    wx.showLoading({
      title: '提交中',
    })
    var questionList = that.data.questionList
    var result = {}
    var corrects = 0,errors = 0
    questionList.forEach(function(item, index){
      var tmp = {}
      if(JSON.stringify(item.answer) == JSON.stringify(item.choosed)){
        corrects ++
        var flag = true
      }else{
        errors ++
        var flag = false
      }
      tmp['answer'] = item.answer
      tmp['choosed'] = item.choosed || ''
      tmp['flag'] = flag
      result[index] = tmp
    })
    const _ = db.command
    db.collection('userInfo').where({
      _openid: that.data.openid
    }).update({
      data: {
        corrects: _.inc(corrects),
      }
    })
    db.collection('userRandomTest').add({
      data: {
        corrects,
        errors,
        add_time: new Date(),
        seconds: parseInt(((new Date()).getTime() - that.data.beginTime)/1000),
        result
      },
      success: res => {
        wx.hideLoading()
        wx.navigateTo({
          url: '../random/result?_id='+res._id,
        })
      },
      fail: err => {
        console.error(err)
      }
    })
    
  },
  onLoad: function(options){
    var that = this

    var openid = wx.getStorageSync('openid')
    if(!openid){
      wx.navigateTo({
        url: '../index/welcome',
      })
      return false
    }
    that.setData({
      openid,
      beginTime: (new Date()).getTime()
    })
  },
  onShow: function () {
    wx.showLoading({
      title: '加载中',
    })
    db.collection('questionBank').aggregate().sample({size:6}).end().then(res => {
      this.setData({
        questionList: res.list
      })
      wx.hideLoading()
    })
    
  },
  showMask: function(){
    this.setData({
      showModal: true
    })
  },
  // 弹出层里面的弹窗
  hideMask: function () {
    this.setData({
      showModal: false
    })
  },
})